import html2canvas from "html2canvas";
import jsPDF from "jspdf";

// elementName: 需要输出PDF的页面id
// htmlTitle: 页面标题
// currentTime: 当前时间

export default function(elementName, htmlTitle, currentTime) {
  let element = document.getElementById(elementName)
  html2canvas(element, {
    useCORS: true,
    allowTaint: false,
    logging: false,
    scale: 1
  }).then(function(canvas) {
    let pdf = new jsPDF('p', 'mm', 'a4') // a4纸 纵向
    let ctx = canvas.getContext('2d')
    let a4w = 190
    let a4h = 257 // a4大小 210mm*297mm 四边保留20mm边距
    let imgHeight = Math.floor(a4h * canvas.width / a4w) // 按a4显示比列换算一页图像的像素高度
    let renderedHeight = 0
    while (renderedHeight < canvas.height) {
      let page = document.createElement('canvas')
      page.width = canvas.width
      page.height = Math.min(imgHeight, canvas.height - renderedHeight) // 可能内容不足一页
      // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
      page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
      pdf.addImage(page.toDataURL('image/jpg', 1.0), 'jpg', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距
      renderedHeight += imgHeight
      if (renderedHeight < canvas.height) { pdf.addPage() } // 如果后面还有内容，添加一个空页
    }
    pdf.save(htmlTitle + currentTime)
  })
}